<template>
	<view class="wrap">
		<view class="search">
			<u-search placeholder="请输入群名称" v-model="query.name" height="80" @custom="search"
				@search="search"></u-search>
			<u-dropdown ref="uDropdown" :close-on-click-mask="uDropdown.mask" :activeColor="uDropdown.activeColor" :borderBottom="uDropdown.borderBottom">
				<u-dropdown-item v-model="query.natureType" @change="natureTypeChange"
					:title="uDropdown.natureTypeTitle" :options="uDropdown.natureTypeOptions"></u-dropdown-item>
				<u-dropdown-item v-model="query.revokeStrategy" @change="revokeStrategyChange"
					:title="uDropdown.revokeStrategyTitle" :options="uDropdown.revokeStrategyOptions"></u-dropdown-item>	
			</u-dropdown>	
		</view>
		<scroll-view class="scroll-list" scroll-y="true" style="width: 100%; height: 87%; margin-top: 5rpx;margin-bottom: 5rpx;" @scrolltolower="loadMore">
			<view>
				<u-swipe-action v-for="(item, index) in list" :show="item.show" :key="item.id" :index="index" 
					:options="dynamicGetSwipeActionOptions(item)" @click="click" 
					@open="open" @close="close" class="uni-list" style="margin-top: 10rpx;margin-bottom: 10rpx;">
					<view @click="toView(item.id)">
						<u-row style="margin: 20rpx;">
							<u-col span="9" class="ellipsisContent" style="font-weight: bold;">
								{{item.name}}
							</u-col>
							<u-col span="3" style="text-align: right;color:gray">
								<font class="fontStyle" >
									{{natureTypeTranslate(item.natureType)}}
								</font>
							</u-col>
						</u-row>
						<u-row style="margin: 20rpx;color:gray">
							<u-col span="10">
								群主：{{item.ownerName}}</br>
								时间：{{item.createTime}}
							</u-col>
							<u-col span="2">
								<u-button v-if="hasPermission('wechatGroupNotice_send')" shape="circle" size="mini" type="primary" @click="handleSendGroupMsg(item.id)">
									发送消息
								</u-button>
							</u-col>
						</u-row>
					</view>
				</u-swipe-action>
			</view>
			<view class="loadmore" @click="loadMore">
				<u-loadmore :status="loadStatus"></u-loadmore>
			</view>
		</scroll-view>
		<view v-if="hasPermission('wechatGroup_add')" class="btn-plus" @click="toAdd">
			<u-icon name="plus-circle-fill" size="90" color="#3d87ff"></u-icon>
		</view>
		<js-general-popup ref="generalPopup" :closeable="true" :zIndex="996" @popupSubmit="doPopupSubmit">
			<wechat-group-notice-form ref="wechatGroupNoticeFormPopup" :chat-id="chatId" :disabled-chat-id="true" :used-source="'popup'">
				<view slot="footerBtns"></view>
			</wechat-group-notice-form>
		</js-general-popup>
	</view>
</template>
<script>
	import JsGeneralPopup from '@/components/js-general-popup/js-general-popup.vue'
	import WechatGroupNoticeForm from '@/pages/wechat/wechatGroupNotice/form.vue'
	export default {
		components: {
			JsGeneralPopup,
			WechatGroupNoticeForm
		},
		data() {
			return {
				query: {
					current: 1,
					size: 20,
					name: ''
				},
				list: [],
				count: 0,
				dictDataOptions: {
					'wechatNatureType': []
				},
				loadStatus: 'loadmore',
				arrow: false,
				bgStyle: {
					'background-color': '#f8f8f8'
				},
				chatId: '',
				uDropdown: {
					mask: true,
					borderBottom: false,
					activeColor: '#2979ff',
					natureTypeOptions: [],
					natureTypeTitle: '群类型',
					revokeStrategyOptions: [],
					revokeStrategyTitle: '回收策略',
				}
			}
		},
		onLoad() {
			// console.log("onLoad...");
			this.initWechatNatureType();
			this.initRevokeStrategy();
			this.loadList();
		},
		onShow() {
			// console.log("onShow...");
			if(uni.getStorageSync("refreshWecahtGroupList") === true){
				uni.removeStorageSync("refreshWecahtGroupList");
				this.search();
			}
		},
		onReady() {
			// console.log("onReady...");
		},
		computed: {
			natureTypeTranslate: function(){
				return (wechatNatureType) => {
					let dictData = this.uDropdown.natureTypeOptions.find(e => e.value == wechatNatureType);
					let wechatNatureTypeName = '';
					if(dictData){
						wechatNatureTypeName = dictData.label;
					}
					return wechatNatureTypeName || wechatNatureType;
				}
			},
			revokeStrategyTranslate: function(){
				return (revokeStrategy) => {
					let dictData = this.uDropdown.revokeStrategyOptions.find(e => e.value == revokeStrategy);
					let revokeStrategyName = '';
					if(dictData){
						revokeStrategyName = dictData.label;
					}
					if(revokeStrategy == '2'){
						// 课程结束半年回收
						revokeStrategyName = '课结半年';
					}
					return revokeStrategyName || revokeStrategy;
				}
			}
		},
		methods: {
			initWechatNatureType() {
				this.$u.api.dictBizData({
					code: "wechat_nature_type"
				}).then(res => {
					let optionList = [];
					let option = {
						'label': '全部',
						'value': ''
					}
					optionList.push(option);
					res.data.forEach((item) => {
						optionList.push({
							'label': item.dictValue,
							'value': item.dictKey
						});
					})
					this.uDropdown.natureTypeOptions = optionList;
				});
			},
			initRevokeStrategy() {
				this.$u.api.dictBizData({
					code: "wechat_revoke_strategy"
				}).then(res => {
					let optionList = [];
					let option = {
						'label': '全部',
						'value': ''
					}
					optionList.push(option);
					res.data.forEach((item) => {
						optionList.push({
							'label': item.dictValue,
							'value': item.dictKey
						});
					})
					this.uDropdown.revokeStrategyOptions = optionList;
				});
			},
			natureTypeChange(index){
				this.list = [];
				this.query.current = 1;
				this.query.natureType = index;
				this.uDropdown.natureTypeTitle=(index===''?'群类型':this.getOptionLabel(this.uDropdown.natureTypeOptions,index));
				this.loadList();
			},
			revokeStrategyChange(index){
				this.list = [];
				this.query.current = 1;
				this.query.revokeStrategy = index;
				this.uDropdown.revokeStrategyTitle=(index===''?'回收策略':this.getOptionLabel(this.uDropdown.revokeStrategyOptions,index));
				this.loadList();
			},
			dynamicGetSwipeActionOptions: function(item){
				const { owner,isExists } = item;
				let uSwipeActionOptions = [];
				if (this.hasPermission('wechatGroup_edit') && owner === this.vuex_userId) {
					uSwipeActionOptions.push({
						text: '编辑',
						style: {
							backgroundColor: '#079cff'
						},
						action: 'edit'
					});
				}
				if (this.hasPermission('wechatGroup_entry') && isExists !== '1') {
					uSwipeActionOptions.push({
						text: '进群',
						style: {
							backgroundColor: '#aa55ff'
						},
						action: 'inGroup'
					});
				}
				if (this.hasPermission('wechatGroup_quit') && owner !== this.vuex_userId && isExists === '1') {
					uSwipeActionOptions.push({
						text: '退群',
						style: {
							backgroundColor: '#dd524d'
						},
						action: 'outGroup'
					});
				}
				if (this.hasPermission('wechatGroup_delGroup') && owner === this.vuex_userId) {
					uSwipeActionOptions.push({
						text: '解散',
						style: {
							backgroundColor: '#dd8928'
						},
						action: 'unGroup'
					});
				}
				return uSwipeActionOptions;
			},
			getFontColorByValue: function(natureType) {
				let color = '#606266';
				// if(natureType == '1'){
				// 	color = 'CornflowerBlue';
				// }else if(natureType == '2'){
				// 	color = 'LightSkyBlue';
				// }else if(natureType == '3'){
				// 	color = 'Orange';
				// }
				return color;
			},
			getTextColorByValue: function(revokeStrategy){
				let color = 'red';
				if(revokeStrategy == '1'){
					color = 'red';
				}else if(revokeStrategy == '2'){
					color = 'orange';
				}
				return color;
			},
			loadList() {
				let vm = this;
				this.$u.api.wechat.wechatGroup.list(this.query).then(res => {
					if (!res.data || !res.data.records || res.data.records == 0) {
						vm.loadStatus = "nomore";
						return;
					}
					vm.list = vm.list.concat(res.data.records);
					vm.list.forEach((item) => {
						item.show = false;
					})
					vm.count = res.total;
					vm.query.current = res.data.current;
					vm.query.size = res.data.size;
					vm.loadStatus = "loadmore";
				});
			},
			loadMore() {
				this.loadStatus = "loading";
				setTimeout(() => {
					this.query.current += 1;
					this.loadList();
				}, 100);
			},
			search() {
				this.list = [];
				this.query.current = 1;
				this.loadList();
			},
			click(rowIndex, btnIndex) {
				let item = this.list[rowIndex];
				let swipeActionOptions = this.dynamicGetSwipeActionOptions(item);
				let { action } = swipeActionOptions[btnIndex];
				if (action == 'edit') {
					this.navTo('form?id=' + item.id + "&mode=edit");
				} else if (action == 'inGroup') {
					this.handleEntryGroup(item.id, rowIndex);
				} else if (action == 'outGroup') {
					this.handleQuitGroup(item.id, rowIndex);
				} else if (action == 'unGroup') {
					this.handleDelGroupUser(item.id, rowIndex);
				} else if (action == 'sendGroupMsg') {
					this.handleSendGroupMsg(item.id);
				}
			},
			toAdd() {
				this.navTo('form?mode=add');
			},
			toView(id) {
				if(this.hasPermission('wechatGroup_view')){
					this.navTo('form?id=' + id + '&mode=view');
				}
			},
			/**
			 * 打开一个swipeAction的同时，需要自动关闭其他的swipeAction
			 * 
			 * @param {Object} index
			 */
			open(index) {
				this.list[index].show = true;
				//下面这行代码不可少，待跟踪源码
				this.$set(this.list, index, this.list[index]);
				this.list.map((val, idx) => {
					if (index != idx) {
						this.list[idx].show = false;
					}
				})
			},
			close(index) {
				this.list[index].show = false;
			},
			navTo(url) {
				uni.navigateTo({
					url: url
				});
			},
			handleEntryGroup(id, rowIndex) {
				let self = this;
				uni.showModal({
					title: '提示',
					content: '确定进入群？',
					showCancel: true,
					success: function(res) {
						if (res.confirm) {
							self.$u.api.wechat.wechatGroup.enterGroup({
								"id": id
							}).then(res => {
								if (res.success) {
									self.list[rowIndex].show = false;
									self.list[rowIndex].isExists = "1";
									//下面这行代码不可少，待跟踪源码
									self.$set(self.list, rowIndex, self.list[rowIndex]);
									self.$u.toast('进入成功！');
									// self.search();
								}
							});
						}
					}
				});
			},
			handleQuitGroup(id, rowIndex) {
				let self = this;
				uni.showModal({
					title: '提示',
					content: '确定退出群？',
					showCancel: true,
					success: function(res) {
						if (res.confirm) {
							self.$u.api.wechat.wechatGroup.quitGroup({
								"id": id
							}).then(res => {
								if (res.success) {
									self.list[rowIndex].show = false;
									self.list[rowIndex].isExists = "0";
									//下面这行代码不可少，待跟踪源码
									self.$set(self.list, rowIndex, self.list[rowIndex]);
									self.$u.toast('退出成功！');
									// self.search();
								}
							});
						}
					}
				});
			},
			handleDelGroupUser(id, rowIndex) {
				let self = this;
				uni.showModal({
					title: '提示',
					content: '确定解散群？',
					showCancel: true,
					success: function(res) {
						if (res.confirm) {
							self.$u.api.wechat.wechatGroup.delGroupUser({
								"id": id
							}).then(res => {
								if (res.success) {
									self.list[rowIndex].show = false;
									//下面这行代码不可少
									self.$set(self.list, rowIndex, self.list[rowIndex]);
									self.$u.toast('解散成功！');
									self.list.splice(rowIndex, 1);
								}
							});
						}
					}
				});
			},
			handleSendGroupMsg(id){
				this.chatId = id;
				this.$refs.generalPopup.open();
			},
			doPopupSubmit() {
				this.$refs.wechatGroupNoticeFormPopup.submit('wechatGroupComp',this.doCloseGeneralPopup);
			},
			doCloseGeneralPopup(){
				this.$refs.generalPopup.close();
			}
		}
	}
</script>

<style lang="scss">
	@import '../../../common/uni.css';
	
	page {
		background-color: #f5f5f5;
	}
	
	.wrap {
		display: flex;
		flex-direction: column;
		height: calc(100vh - var(--window-top) - var(--window-bottom)); // 视高 - 内容区顶部 - 内容区底部
		width: 100%;
	}
	
	.search{
		height:90px;
		background-color: #ffffff;
		background-size: 450px;
	}
	
	.fontStyle{
		font-weight: bold;
	}
	
	.ellipsisContent {
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
	}
	.textBlock {
		padding: 3rpx;
		border-width: 1px;
		border-style: solid;
	}
</style>